package QueryExcecution;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;

import queryClass.Queries;
import DB.DAOManager;

public class CalculatePollResult {
	Queries q=new Queries();
	PreparedStatement pstmt=null;
	DAOManager dao;
	ResultSet rs,newrs;
	public double[] calculateResult(int choice){
		int rows = 0;
		int pollid=0;
		double result[] =new double[3];
		double opt1=0,opt2=0,opt3=0;
		try {
			dao = new DAOManager();
			Connection conn=dao.getConnection();
			String recieve=q.calculatepoll;
			pstmt=conn.prepareStatement(recieve);	
			rs=pstmt.executeQuery();
			while(rs.next()){
				pollid=rs.getInt("pollid");
				
			}///while ends ////
			String update=null;
			pstmt=null;
			if(choice==1){
				update=q.updateYes;
				update=update+pollid;
				System.out.println("update query is =========="+update);
				pstmt=conn.prepareStatement(update);
				int row =pstmt.executeUpdate();
			}
			if(choice==2){
				update=q.updateNo;
				update=update+pollid;
				System.out.println("update query is =========="+update);
				pstmt=conn.prepareStatement(update);
				int row =pstmt.executeUpdate();
			}
			if(choice==3){
				update=q.updateCantSay;
				update=update+pollid;
				System.out.println("update query is =========="+update);
				pstmt=conn.prepareStatement(update);
				int row =pstmt.executeUpdate();
			}
			pstmt=null;
			String calculate=q.calculatepoll;
			pstmt=conn.prepareStatement(calculate);	
			newrs=pstmt.executeQuery();
			while(newrs.next()){
				pollid=newrs.getInt("pollid");
				opt1=(double)newrs.getInt("yes");
				opt2=(double)newrs.getInt("no");
				opt3=(double)newrs.getInt("cantsay");

			}///while ends ////
			double total=opt1+opt2+opt3;
			 DecimalFormat f = new DecimalFormat("##.00");

			double opt1perc=(double)((opt1*100)/total);
			String Sopt1perc=f.format(opt1perc);
			opt1perc=Double.parseDouble(Sopt1perc);
			double opt2perc=(double)((opt2*100)/total);
			String Sopt2perc =f.format(opt2perc);
			opt2perc=Double.parseDouble(Sopt2perc);

			double opt3perc=(double)((opt3*100)/total);
			String Sopt3perc =f.format(opt3perc);
			opt3perc=Double.parseDouble(Sopt3perc);

System.out.println("vaat lagli!!");
			System.out.println("option1-------"+opt1perc+"option2---------"+opt2perc+"option3-----------"+opt3perc);
			result[0]=opt1perc;
			result[1]=opt2perc;
			result[2]=opt3perc;
			return result;
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
		}
}
